package com.central.apps.handler.MaterialInventory;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.common.util.DeptUtil;
import com.central.app.handler.factory.HandlerFactory;
import com.central.app.service.HandlerService;
import com.central.apps.service.CustomizationService;
import com.central.app.common.util.BLuntil;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.SysUserUtil;
import com.central.common.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WareManageHandler extends BaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private CustomizationService customizationService;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {

        List<Map<String, Object>> bySql = handlerService.findBySql("select storenum,schouse from gq_store where id =" + id);
        String storenum = MapUtils.getString(bySql.get(0), "storenum");
        String schouse = MapUtils.getString(bySql.get(0), "schouse");//报废库
        String isor="是";
        List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_store where schouse='" + isor + "'");
        if (CollectionUtils.isNotEmpty(bySql2)){
            if (schouse.equals("是")){
                return "已设置报废库，请勿重复！";
            }
        }
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_areashelf where storenum='" + storenum + "'");
        if (CollectionUtils.isEmpty(bySql1)){
            return "请添加货位数据！";
        }

        return super.beforeExcuteFlow(app, id, flowNode, op);
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if("gq_areashelf".equals(objName)){
            //新增保存时提示
            if(!isUpdate){
                String shelfnum = MapUtils.getString(data, "shelfnum");
                List<Map<String, Object>> list = handlerService.findBySql("select id from gq_areashelf where shelfnum='" + shelfnum + "'");
                if (CollectionUtils.isNotEmpty(list)){
                    throw new ServiceException("货位编号已存在，请重新编辑");
                }
            }
        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("storeApp".equals(app)){
            if ("gq_areashelf".equals(objName)){
                String storenum = MapUtils.getString(data, "storenum");
                List<Map<String, Object>> bySql = handlerService.findBySql("SELECT\n" +
                        "\t\tcount(0) as number\n" +
                        "\tFROM\n" +
                        "\t\t(\n" +
                        "\t\tSELECT\n" +
                        "\t\t\tdistinct rowdesc \n" +
                        "\t\tFROM\n" +
                        "\t\t\tgq_areashelf \n" +
                        "\t\tWHERE\n" +
                        "\t\tstorenum = '" + storenum + "' \n" +
                        "\t) TOTAL");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT\n" +
                        "\t\tcount(0) as numbers\n" +
                        "\tFROM\n" +
                        "\t\t(\n" +
                        "\t\tSELECT\n" +
                        "\t\t\tdistinct itemnum \n" +
                        "\t\tFROM\n" +
                        "\t\t\tgq_invbalances \n" +
                        "\t\tWHERE\n" +
                        "\t\tstorenum = '" + storenum + "' \n" +
                        "\t) TOTAL");

                Integer number = MapUtils.getInteger(bySql.get(0), "number");
                Float numbers = MapUtils.getFloat(bySql1.get(0), "numbers");
                handlerService.updateBySql("update gq_store set number="+number+",numbers="+numbers+" where storenum='"+storenum+"'");
            }
        }
        super.afterSave(app, objName, data, isUpdate);
    }

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        //再掉库房管理列表接口之前，先调一下这个接口，将库房里的物料数量更新
        if("storeApp".equals(app)){
            if("findStoreList".equals(type)){
                //更新物料数量   货位数量
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_store");
                if(CollectionUtils.isNotEmpty(bySql)){
                    for (Map<String, Object> map : bySql) {
                        String storenum = MapUtils.getString(map, "storenum");//仓库编号
                        List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT COUNT(0) as numbers from gq_invbalances where storenum = '" + storenum + "'");
                        Float numbers=0f;
                        int number=0;
                        if(CollectionUtils.isNotEmpty(bySql1)){
                            numbers = MapUtils.getFloat(bySql1.get(0), "numbers");
                        }
                        //更新库房里库位数量
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select count(0) as number from gq_areashelf where storenum = '" + storenum + "'");
                        if(CollectionUtils.isNotEmpty(bySql2)){
                            number = MapUtils.getInteger(bySql2.get(0), "number");
                        }
                        Integer id = MapUtils.getInteger(map, "id");
                        handlerService.findBySql("update gq_store set numbers = '" + numbers + "', number = '" + number + "' where id = '" + id + "'");
                    }
                }
            }

            if ("findStorePage".equals(type)) {
                LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
                String userName = loginUser.getUsername();
                String deptCode = loginUser.getDeptcode();

                // 获取父子部门数据
                String deptCodeString = DeptUtil.getDeptString(deptCode);

                StringBuilder sql = new StringBuilder();
                sql.append("select * from (select * from gq_store where schouse = '是' union all select * from gq_store where schouse = '否'");

                if (!"admin".equals(userName)) {
                    sql.append(" and deptcode in (").append(deptCodeString).append(")) t");
                } else {
                    sql.append(") t");
                }

                return customizationService.findPage(params, sql.toString());
            }
        }

        return null;
    }

    @Override
    public String validateDelete(String app, String objName, Long id) throws Exception {
        if("storeApp".equals(app)){
            if("gq_areashelf".equals(objName)){
                List<Map<String, Object>> bySql = handlerService.findBySql("select shelfnum,storenum from gq_areashelf where id = " + id);
                if(CollectionUtils.isNotEmpty(bySql)){
                    String shelfnum = MapUtils.getString(bySql.get(0), "shelfnum");//货位编号
                    String storenum = MapUtils.getString(bySql.get(0), "storenum");//库房编号
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select SUM(curbal) as itemquantity from gq_invbalances where binnum = '" + shelfnum + "' and storenum = '" + storenum + "'");
                    if(CollectionUtils.isNotEmpty(bySql1)){
                        Integer itemquantity = MapUtils.getInteger(bySql1.get(0), "itemquantity");
                        if(StringUtils.isNotBlank(MapUtils.getString(bySql1.get(0), "itemquantity"))){
                            if(itemquantity>=0){
                                return "该货位下存在库存余量，不允许删除";
                            }
                        }
                    }
                }
            }
        }
        return super.validateDelete(app, objName, id);
    }

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
        if("storeApp".equals(app)){
            if("gq_store".equals(objName)){
                //保存前验证库房编码/名称不能重复
                String id = MapUtils.getString(data, "id");
                String storenum = MapUtils.getString(data, "storenum");
                String storedesc = MapUtils.getString(data, "storedesc");
                if(StringUtils.isNotBlank(id)){
                    //修改保存
                    List<Map<String, Object>> bySql = handlerService.findBySql("select id from gq_store where storenum = '" + storenum + "'");
                    if(CollectionUtils.isNotEmpty(bySql)){
                        Map<String, Object> map = bySql.get(0);
                        if(!MapUtils.getString(map,"id").equals(id)){
                            return "该库房编码在系统中已存在，请修改后保存！";
                        }
                    }
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select id from gq_store where storedesc = '" + storedesc + "'");
                    if(CollectionUtils.isNotEmpty(bySql1)){
                        Map<String, Object> map = bySql1.get(0);
                        if(!MapUtils.getString(map,"id").equals(id)){
                            return "该库房名称在系统中已存在，请修改后保存！";
                        }
                    }
                }else{
                    //新增保存
                    List<Map<String, Object>> bySql = handlerService.findBySql("select id from gq_store where storenum = '" + storenum + "'");
                    if(CollectionUtils.isNotEmpty(bySql)){
                        return "该库房编码在系统中已存在，请修改后保存！";
                    }
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select id from gq_store where storedesc = '" + storedesc + "'");
                    if(CollectionUtils.isNotEmpty(bySql1)){
                        return "该库房名称在系统中已存在，请修改后保存！";
                    }
                }
            }
        }
        return super.validateSave(app, objName, data);
    }
}
